<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Traits\LogsActivity;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class AdminUserController extends Controller
{
    use LogsActivity;
    /**
     * 显示用户列表
     */
    public function index(Request $request): Response
    {
        $query = User::query();

        // 搜索
        if ($request->filled('search')) {
            $search = $request->search;
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                    ->orWhere('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%");
            });
        }

        $users = $query->withCount(['addresses'])
            ->orderBy('created_at', 'desc')
            ->paginate(20)
            ->withQueryString();

        return Inertia::render('Admin/Users/Index', [
            'users' => $users,
            'filters' => [
                'search' => $request->search ?? '',
            ]
        ]);
    }

    /**
     * 显示用户详情
     */
    public function show(User $user): Response
    {
        $user->load([
            'addresses' => function ($query) {
                $query->orderBy('is_default', 'desc')
                    ->orderBy('created_at', 'desc');
            }
        ]);

        // 获取用户订单统计
        $orderStats = [
            'total_orders' => $user->orders()->count(),
            'total_spent' => $user->orders()
                ->where('payment_status', 'paid')
                ->sum('total_amount'),
            'pending_orders' => $user->orders()
                ->whereIn('status', ['pending', 'processing'])
                ->count(),
        ];

        // 获取最近订单
        $recentOrders = $user->orders()
            ->with(['items'])
            ->orderBy('created_at', 'desc')
            ->limit(10)
            ->get()
            ->map(function ($order) {
                return [
                    'id' => $order->id,
                    'order_number' => $order->order_number,
                    'total_amount' => $order->total_amount,
                    'status' => $order->status,
                    'payment_status' => $order->payment_status,
                    'created_at' => $order->created_at,
                    'items_count' => $order->items->count(),
                ];
            });

        return Inertia::render('Admin/Users/Show', [
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'birthday' => $user->birthday,
                'bio' => $user->bio,
                'email_verified_at' => $user->email_verified_at,
                'created_at' => $user->created_at,
                'updated_at' => $user->updated_at,
                'addresses' => $user->addresses,
            ],
            'orderStats' => $orderStats,
            'recentOrders' => $recentOrders,
        ]);
    }

    /**
     * 显示编辑用户表单
     */
    public function edit(User $user): Response
    {
        return Inertia::render('Admin/Users/Edit', [
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'email' => $user->email,
                'phone' => $user->phone,
                'birthday' => $user->birthday,
                'bio' => $user->bio,
                'email_verified_at' => $user->email_verified_at,
            ],
        ]);
    }

    /**
     * 更新用户信息
     */
    public function update(Request $request, User $user)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'email' => 'nullable|string|email|max:255|unique:users,email,' . $user->id,
            'phone' => 'nullable|string|max:20|unique:users,phone,' . $user->id,
            'birthday' => 'nullable|date',
            'bio' => 'nullable|string|max:500',
        ]);

        $user->update($request->only(['name', 'email', 'phone', 'birthday', 'bio']));

        // 记录日志
        $this->logUpdate(
            module: 'users',
            itemName: $user->name,
            model: $user
        );

        return redirect()->route('users.show', $user)
            ->with('success', '用户信息更新成功！');
    }

    /**
     * 重置用户密码
     */
    public function resetPassword(Request $request, User $user)
    {
        $request->validate([
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        $user->update([
            'password' => Hash::make($request->password),
        ]);

        return redirect()->back()
            ->with('success', '密码重置成功！');
    }

    /**
     * 切换用户邮箱验证状态
     */
    public function toggleEmailVerification(User $user)
    {
        if ($user->email_verified_at) {
            $user->update(['email_verified_at' => null]);
            $message = '已取消邮箱验证';
        } else {
            $user->update(['email_verified_at' => now()]);
            $message = '已标记为已验证';
        }

        return redirect()->back()
            ->with('success', $message);
    }

    /**
     * 删除用户（软删除或标记为禁用）
     */
    public function destroy(User $user)
    {
        // 检查用户是否有未完成的订单
        $pendingOrders = $user->orders()
            ->whereIn('status', ['pending', 'processing', 'shipped'])
            ->count();

        if ($pendingOrders > 0) {
            return redirect()->back()
                ->with('error', "该用户有 {$pendingOrders} 个未完成的订单，无法删除！");
        }

        // 这里可以实现软删除或禁用逻辑
        // 暂时不删除，只是示例
        return redirect()->back()
            ->with('error', '用户删除功能暂未启用，建议使用禁用功能');
    }
}
